<template>
  <div class="app-container">
    <HomeownerForm ref="homeownerFormRef" v-model="form" :disabled="isReadOnlyHomeowner" mode="edit" />
    <br></br>
    <div class="flex items-center justify-between">
      <el-text tag="b">关联合同</el-text>
      <el-button @click="homeownersContractAdd" type="primary" v-hasPermi="['fang:homeowners:addcontract']">新增</el-button>
    </div>
    <hr>
    </hr>
    <div>
      <el-table v-loading="loading" :data="form.hcList" style="width: 100%">
        <el-table-column label="产证编号" align="center" prop="houseCertificateNumber" />
        <el-table-column label="合同编号" align="center" prop="contractNumber" width="160" />
        <el-table-column label="合同状态" align="center" prop="contractStatus" :formatter="contractStatusText" />
        <el-table-column label="合同开始" align="center" prop="contractStartTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.contractStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同终止" align="center" prop="contractEndTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.contractEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="房源信息" align="center" prop="address" width="200" />
        <el-table-column label="户型/面积" align="center" prop="houseArea" />
        <el-table-column label="租金及管理费描述" align="center" prop="rentFeeDescribe" width="200" />
        <el-table-column label="房源状态" align="center" prop="houseStatus">
          <template #default="scope">
            <el-text>{{ getHouseStatusText(scope.row.houseStatus) }}</el-text>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="homeownersContractDetai(scope.row)"
              v-hasPermi="['fang:homeowners:querycontract']">详情</el-button>
            <el-button link type="primary" @click="homeownersContractDetai(scope.row)"
              v-hasPermi="['fang:homeowners:detailcontract']"
              v-show="scope.row.contractStatus == HOMEOWNER_CONTRACT_STATUS.VALID">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <HomeownerContractEditDialog 
      v-model="dialogVisible" 
      :homeownerId="form.id"
      :contractId="editingContractId"
      @saved="initdata"
      @terminated="initdata"
      @deleted="initdata"
      @closed="handleDialogClosed"
    />

  </div>

</template>

<script setup name="hcdetial">
import auth from '@/plugins/auth'
import {
  getHomeowners,
  terminateHomeownersContract, deleteDraftHomeownersContract, saveDraftHomeownersContract, saveHomeownersContract
} from "@/api/fang/homeowners"
import { getHouseStatusText, HOMEOWNER_CONTRACT_STATUS, getHomeownerContractStatusText } from '@/utils/enums'
import { getFileObj } from '@/utils/tools'
import { parseTime } from "@/utils/ruoyi"
import HomeownerContractEditDialog from '@/components/HomeownerContractEditDialog/index.vue'
import HomeownerForm from './components/HomeownerForm.vue'

const { proxy } = getCurrentInstance()

const contract_status_dic = [
  { value: '1', label: '有效' },
  { value: '2', label: '无效' },
  { value: '0', label: '草稿' }
]
function contractStatusText(row, column, cellValue) {
  return getHomeownerContractStatusText(cellValue)
}

const open = ref(false)
const loading = ref(false)
const route = useRoute()
const homeownerFormRef = ref(null)

const dialogVisible = ref(false)
const editingContractId = ref(null)

const data = reactive({
  form: {},
  queryParams: {},
  // contractForm: {}

})

const { form } = toRefs(data)

// 页面只读：无业主信息编辑权限即只读
const isReadOnlyHomeowner = computed(() => !auth.hasPermi('fang:homeowners:editinfo'))

// 移除未使用的临时状态与校验配置



// 表单重置
// function reset() {

//   form.value = {
//     id: null,
//     name: null,
//     phone: null,

//     isUse: null,

//     identityNumber: null,
//     identityFile: null,
//     identityFileVo: [],
//     identityFileUrl: null,
//     identityFileTwo: null,
//     identityFileTwoVo: [],
//     identityFileTwoUrl: null,
//   }
//   homeownerFormRef.value?.resetFields()
// }

// function resetContract() {
//   contractForm.value = {
//     id: null,
//     homeownersId: null,
//     houseNumber: null,

//     contractStartTime: null,
//     contractEndTime: null,
//     houseArea: null,
//     houseCertificateNumber: null,
//     address: null,
//     rentFeeDescribe: null,
//     houseDescribe: null,

//   }
//   proxy.resetForm("homeownersContractRef")
// }

// 取消按钮
// function cancel() {
//   open.value = false
//   reset()
// }



// 业主信息保存逻辑已交由 HomeownerForm 内部处理

/**
 * 初始化业主详情页，业主基本信息+房源列表
 */
function initdata() {

  console.log("initdata:")
  const tableId = route.params && (route.params.homeownerId || route.params.tableId)
  console.log("tableId=:" + tableId)
  // 获取表详细信息
  loading.value = true
  getHomeowners(tableId).then(response => {
    form.value = response.data
    form.value.identityFileVo = getFileObj(response.data.identityFileVo)
    form.value.identityFileTwoVo = getFileObj(response.data.identityFileTwoVo)
  }
  ).finally(() => {
    loading.value = false
  })



  // if (tableId > 0) {
  //   console.log("tableId=:" + tableId)
  //   // 获取表详细信息
  //   loading.value = true
  //   getHomeowners(tableId).then(response => {
  //     form.value = response.data
  //     form.value.identityFileVo = getFileObj(response.data.identityFileVo)
  //     form.value.identityFileTwoVo = getFileObj(response.data.identityFileTwoVo)
  //   }
  //   ).finally(() => {
  //     loading.value = false
  //   })
  // } else {
  //   console.log("homeownersContractId11:")
  //   console.log("homeownersContractId:" + form.homeownersContractId)
  //   reset()

  // }
}




/**********************合同详情********************* */

/**
 * 合同详情
 * @param row 
 */
function homeownersContractDetai(row) {
  editingContractId.value = row.id
  dialogVisible.value = true
}

/** 发送续期提醒**/
// function renewalHomeownersReminderCl() {
//   open.value = true
// }
/**一键下载全部合同 **/
// function downloadHomeownersContractCl() {
//   open.value = true
// }

/** 终止合同**/
// function terminateContractCl() {

//   const id = contractForm.value.id
//   terminateHomeownersContract(id).then(response => {
//     proxy.$modal.msgSuccess("操作成功")
//     resetContract()
//     //open.value = false
//     initdata()
//   })
//   open.value = false

// }
// function deleteHomeownersContractDraftCl() {
//   // open.value = true

//   const id = contractForm.value.id
//   deleteDraftHomeownersContract(id).then(response => {
//     proxy.$modal.msgSuccess("删除成功")
//     resetContract()
//     open.value = false
//     initdata()
//   })
// }


/** 存草稿**/
// function saveDraftHomeownersContractCl() {

//   proxy.$refs["homeownersContractRef"].validate(valid => {
//     if (valid) {
//       console.log("form.id")
//       console.log(form.value.id)

//       contractForm.value.homeownersId = form.value.id

//       saveDraftHomeownersContract(contractForm.value).then(response => {
//         proxy.$modal.msgSuccess("修改成功")
        
//         // 关闭弹窗并刷新合同列表
//         open.value = false
//         resetContract()
//         initdata()

//       })

//     }
//   })
// }



/** 保存合同**/
// function saveHomeownersContractCl() {

//   proxy.$refs["homeownersContractRef"].validate(valid => {
//     if (valid) {
//       console.log("form.id")
//       console.log(form.value.id)

//       const contractFileVo = contractForm.value.contractFileVo?.[0] ?? {};
//       const managementFeeFileVo = contractForm.value.managementFeeFileVo?.[0] ?? {};
//       const handoverFileVo = contractForm.value.handoverFileVo?.[0] ?? {};
//       console.log(contractForm.value)

//       const data = {
//         ...contractForm.value,
//         homeownersId: form.value.id,
//         contractFile: contractFileVo.id,
//         contractFileUrl: contractFileVo.filePath,
//         contractFileVo: {
//           id: contractFileVo.id,
//           filePath: contractFileVo.filePath,
//           originalName: contractFileVo.originalName,
//         },
//         managementFeeFile: managementFeeFileVo.id,
//         managementFeeFileUrl: managementFeeFileVo.filePath,
//         managementFeeFileVo: {
//           id: managementFeeFileVo.id,
//           filePath: managementFeeFileVo.filePath,
//           originalName: managementFeeFileVo.originalName,
//         },
//         handoverFile: handoverFileVo.id,
//         handoverFileUrl: handoverFileVo.filePath,
//         handoverFileVo: {
//           id: handoverFileVo.id,
//           filePath: handoverFileVo.filePath,
//           originalName: handoverFileVo.originalName,
//         },
//       }

//       console.log(data)

//       saveHomeownersContract(data).then(response => {
//         proxy.$modal.msgSuccess("修改成功")
//         // 关闭弹窗并刷新合同列表
//         open.value = false
//         resetContract()
//         initdata()

//       })

//     }
//   })
// }


function homeownersContractAdd() {
  editingContractId.value = null
  dialogVisible.value = true
}

function handleDialogClosed() {
  editingContractId.value = null
}


initdata()



</script>